<template>
  <view class="travel-list">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
        <input
          class="search-input"
          v-model="searchKeyword"
          placeholder="搜索关键词"
          @confirm="searchTravels"
        />
        <text class="search-btn" :class="{ searching }" @click="searchTravels">
          {{ searching ? '搜索中...' : '搜索' }}
        </text>
      </view>
    </view>

    <!-- 大交通选项切换 -->
    <view class="transportation-filter" v-if="showTransportationFilter">
      <view class="filter-options">
        <view 
          class="filter-option" 
          :class="{ active: transportationFilter === 'all' }"
          @click="setTransportationFilter('all')"
        >
          全部
        </view>
        <view 
          class="filter-option" 
          :class="{ active: transportationFilter === 'include' }"
          @click="setTransportationFilter('include')"
        >
          包含大交通
        </view>
        <view 
          class="filter-option" 
          :class="{ active: transportationFilter === 'exclude' }"
          @click="setTransportationFilter('exclude')"
        >
          不含大交通
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 左侧目的地筛选 -->
      <view class="destination-sidebar" v-if="showDestinationFilter">
        <scroll-view class="destination-scroll" scroll-y="true">
          <view class="destination-list">
            <view
              class="destination-item"
              :class="{ active: selectedDestination === null }"
              @click="selectDestination(null)"
            >
              <text class="destination-text">全部</text>
            </view>
            <view
              class="destination-item"
              v-for="destination in destinationList"
              :key="destination"
              :class="{ active: selectedDestination === destination }"
              @click="selectDestination(destination)"
            >
              <text class="destination-text">{{ destination }}</text>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 右侧旅行商品列表 -->
      <view class="travel-content">
        <scroll-view 
          class="travel-list-container"
          scroll-y="true"
          @scrolltolower="loadMore"
        >
          <view
            class="travel-item"
            v-for="travel in travelList"
            :key="travel.id"
            @click="goToDetail(travel.id)"
          >
            <view class="travel-image-wrapper">
              <image
                :src="travel.cover || '/static/image/logo.png'"
                class="travel-image"
                mode="aspectFill"
                lazy-load
                @error="onImageError"
              ></image>
            </view>
            <view class="travel-info">
              <view class="travel-header">
                <text class="travel-name">{{ travel.name }}</text>
                <view class="travel-price-section">
                  <text class="travel-sales">已售 {{ travel.sales || 0 }}</text>
                  <view class="price-info">
                    <text class="travel-price">{{ travel.price_text || 0 }}元/人起</text>
                    <text class="travel-price-tag" v-if="userInfo.user_type === 3">佣金{{ travel.share_price || 0 }}元</text>
                  </view>
                </view>
              </view>
            </view>
          </view>

          <!-- 加载更多状态 -->
          <view class="bottom-loading" v-if="loading && travelList.length > 0">
            <text class="loading-text">加载中...</text>
          </view>

          <!-- 没有更多数据 -->
          <view class="no-more" v-if="!hasMore && travelList.length > 0">
            <text class="no-more-text">没有更多数据了</text>
          </view>

          <!-- 空状态 -->
          <view class="empty-state" v-if="travelList.length === 0 && !loading && !loadError">
            <image src="/static/image/no_permission.png" class="empty-image" mode="aspectFit"></image>
            <text class="empty-text">暂无数据</text>
          </view>

          <!-- 错误状态 -->
          <view class="error-state" v-if="loadError && travelList.length === 0">
            <image src="/static/image/no_permission.png" class="error-image" mode="aspectFit"></image>
            <text class="error-text">加载失败</text>
            <text class="error-tip">请检查网络连接后重试</text>
            <view class="retry-btn" @click="refreshList">重新加载</view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import Navbar from "../../components/Navbar.vue";
import api from "../../config/api.js";

export default {
  components: { Navbar },
  data() {
    return {
      travelList: [],
      searchKeyword: '',
      categoryId: null,
      page: 1,
      pageSize: 20,
      hasMore: true,
      loading: false,
      searchTimer: null,
      loadError: false,
      searching: false,
      showTransportationFilter: false, // 是否显示大交通筛选
      transportationFilter: 'all', // 大交通筛选选项：all-全部，include-包含大交通，exclude-不含大交通
      categoryDetail: null, // 分类详情
      showDestinationFilter: true, // 是否显示目的地筛选
      destinationList: [], // 目的地列表
      selectedDestination: null // 选中的目的地ID
    }
  },
  onLoad(options) {
    console.log('旅行商品列表页面加载，参数:', options);

    // 如果有搜索关键词参数
    if (options.keyword) {
      this.searchKeyword = options.keyword;
    }
    // 如果有分类参数
    if (options.categoryId) {
      this.categoryId = parseInt(options.categoryId);
      // 获取分类详情
      this.loadCategoryDetail();
    }

    this.loadTravelList();
    this.loadDestinationList();
  },
  onPullDownRefresh() {
    this.refreshList();
  },
  onShow() {
    console.log('旅行商品列表页面显示');

    // 重置页面标题
    uni.setNavigationBarTitle({
      title: '旅行商品'
    });
  },
  onReady() {
    console.log('旅行商品列表页面渲染完成');
  },
  onUnload() {
    // 页面卸载时清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    console.log('旅行商品列表页面卸载');
  },
  onHide() {
    console.log('旅行商品列表页面隐藏');
  },
  onShareAppMessage() {
    return {
      title: '旅行商品 - 精选旅行',
      path: '/pages/travel/travel',
      imageUrl: '/static/image/logo.png'
    };
  },
  onShareTimeline() {
    return {
      title: '旅行商品 - 精选旅行',
      imageUrl: '/static/image/logo.png'
    };
  },
  methods: {
    getSharePrice(skus) {
      if (skus && skus.length > 0) {
        // 最高的佣金
        return skus.reduce((min, sku) => Math.min(min, sku.share_price), 0);
      }
      return 0;
    },
    // 加载旅行商品列表
    loadTravelList(isRefresh = false) {
      if (this.loading) return;

      this.loading = true;

      if (isRefresh) {
        this.page = 1;
        this.hasMore = true;
      }

      console.log('加载旅行商品列表:', {
        page: this.page,
        pageSize: this.pageSize,
        searchKeyword: this.searchKeyword,
        categoryId: this.categoryId
      });

      const params = {
        status: 1 // 只获取启用的旅行商品
      };

      // 添加分类筛选
      if (this.categoryId !== null) {
        params.category_id = this.categoryId;
      }

      // 添加搜索关键词
      if (this.searchKeyword.trim()) {
        params.name = this.searchKeyword.trim();
      }

      // 添加大交通筛选
      if (this.showTransportationFilter && this.transportationFilter !== 'all') {
        if (this.transportationFilter === 'include') {
          params.transportation_flag = 1; // 包含大交通
        } else if (this.transportationFilter === 'exclude') {
          params.transportation_flag = 0; // 不含大交通
        }
      }

      // 添加目的地筛选
      if (this.showDestinationFilter && this.selectedDestination !== null) {
        params.destination_city = this.selectedDestination;
      }

      api.getTravelPage({
        ...params,
        pageNo: this.page,
        pageSize: this.pageSize,
        sort: 'price_text,asc'
      }).then(result => {
        console.log('API返回结果:', result);

        const data = result.list || [];

        // 数据验证
        if (!Array.isArray(data)) {
          console.error('API返回的数据格式错误:', data);
          throw new Error('数据格式错误');
        }

        if (isRefresh) {
          this.travelList = data;
        } else {
          this.travelList = [...this.travelList, ...data];
        }

        // 检查是否还有更多数据
        this.hasMore = data.length >= this.pageSize;
        this.loadError = false;
        this.searching = false;
      }).catch(error => {
        console.error('加载旅行商品列表失败:', error);
        this.loadError = true;
        this.searching = false;

        if (isRefresh) {
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          });
        }
      }).finally(() => {
        this.loading = false;
        uni.stopPullDownRefresh();
      });
    },

    // 刷新列表
    refreshList() {
      this.loadTravelList(true);
    },

    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.page++;
        this.loadTravelList();
      }
    },

    // 搜索旅行商品
    searchTravels() {
      this.searching = true;
      // 清空列表并重置分页
      this.travelList = [];
      this.page = 1;
      this.hasMore = true;
      this.loadTravelList(true);
    },

    // 搜索输入处理（防抖）
    onSearchInput() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      this.searchTimer = setTimeout(() => {
        this.searchTravels();
      }, 800);
    },

    // 获取最低价格
    getMinPrice(travel) {
      // 如果旅行商品有SKU，显示最低价格
      if (travel.skus && travel.skus.length > 0) {
        const minPriceSku = travel.skus.reduce((min, sku) =>
          sku.price < min.price ? sku : min
        );
        return minPriceSku.price || 0;
      }
      // 否则显示旅行商品基础价格
      return travel.price || 0;
    },

    // 获取原价
    getOriginalPrice(travel) {
      // 如果旅行商品有SKU，显示最高原价
      if (travel.skus && travel.skus.length > 0) {
        const maxOriginalPriceSku = travel.skus.reduce((max, sku) =>
          (sku.original_price || 0) > (max.original_price || 0) ? sku : max
        );
        return maxOriginalPriceSku.original_price || 0;
      }
      // 否则显示旅行商品原价
      return travel.original_price || travel.price || 0;
    },

    // 获取库存状态
    getStockStatus(travel) {
      // 如果旅行商品有SKU，计算总库存
      if (travel.skus && travel.skus.length > 0) {
        const totalStock = travel.skus.reduce((sum, sku) => sum + (sku.stock || 0), 0);
        if (totalStock <= 0) {
          return '无货';
        } else if (totalStock < 10) {
          return '库存紧张';
        }
      } else {
        // 否则使用旅行商品基础库存
        if (travel.stock !== undefined) {
          if (travel.stock <= 0) {
            return '无货';
          } else if (travel.stock < 10) {
            return '库存紧张';
          }
        }
      }
      return '';
    },

    // 图片加载错误处理
    onImageError(e) {
      console.log('图片加载失败:', e);
    },

    // 跳转到旅行商品详情
    goToDetail(travelId) {
      console.log('跳转到旅行商品详情:', travelId);
      uni.navigateTo({
        url: `/pages/travel/detail?id=${travelId}`
      });
    },

    // 加载分类详情
    loadCategoryDetail() {
      if (!this.categoryId) return;

      console.log('加载分类详情:', this.categoryId);
      
      api.getTravelCategoryDetail(this.categoryId).then(result => {
        console.log('分类详情API返回结果:', result);
        
        this.categoryDetail = result;
        
        // // 判断是否显示大交通筛选
        // if (result && result.transportation_flag === 1) {
        //   this.showTransportationFilter = true;
        // } else {
        //   this.showTransportationFilter = false;
        // }
        
        // 判断是否显示目的地筛选
        // if (result && result.destination_group_flag === 1) {
        //   this.showDestinationFilter = true;
        //   this.loadDestinationList();
        // } else {
        //   this.showDestinationFilter = false;
        // }
        // 设置标题
        uni.setNavigationBarTitle({
          title: this.categoryDetail.name
        });
      }).catch(error => {
        console.error('加载分类详情失败:', error);
      });
    },

    // 设置大交通筛选
    setTransportationFilter(filter) {
      this.transportationFilter = filter;
      // 清空列表并重置分页
      this.travelList = [];
      this.page = 1;
      this.hasMore = true;
      this.loadTravelList(true);
    },

    // 加载目的地列表
    loadDestinationList() {
      console.log('加载目的地列表');
      
      this.$api.getDestinationCityGroupList({ category_id: this.categoryId }).then(result => {
        console.log('目的地列表API返回结果:', result);
        
        const data = result || [];
        
        // 数据验证
        if (!Array.isArray(data)) {
          console.error('目的地列表API返回的数据格式错误:', data);
          return;
        }
        
        this.destinationList = data;
      }).catch(error => {
        console.error('加载目的地列表失败:', error);
      });
    },

    // 选择目的地
    selectDestination(destinationId) {
      this.selectedDestination = destinationId;
      // 清空列表并重置分页
      this.travelList = [];
      this.page = 1;
      this.hasMore = true;
      this.loadTravelList(true);
    }
  }
}
</script>
<style lang="scss">
page {
  background-color: #f5f5f5;
  height: 100vh;
  overflow: hidden;
}
.travel-list {
  height: 100%;
  overflow: hidden;
  padding-bottom: 20rpx;
  display: flex;
  flex-direction: column;

  // 搜索栏
  .search-bar {
    background: #FFFFFF;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    flex-shrink: 0;

    .search-input-wrapper {
      display: flex;
      align-items: center;
      background: #f8f8f8;
      border-radius: 24rpx;
      padding: 16rpx 24rpx;

      .search-icon {
        width: 32rpx;
        height: 32rpx;
        margin-right: 16rpx;
      }

      .search-input {
        flex: 1;
        font-size: 28rpx;
        color: #333333;
      }

      .search-btn {
        font-size: 28rpx;
        color: #333;
        padding-left: 16rpx;

        &.searching {
          color: #999999;
        }
      }
    }
  }

  // 大交通筛选
  .transportation-filter {
    background: #FFFFFF;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #f0f0f0;
    flex-shrink: 0;

    .filter-options {
      display: flex;
      gap: 16rpx;

      .filter-option {
        flex: 1;
        text-align: center;
        padding: 12rpx 24rpx;
        border-radius: 20rpx;
        font-size: 26rpx;
        color: #666666;
        background: #f5f5f5;
        border: 2rpx solid transparent;
        transition: all 0.3s ease;

        &.active {
          color: #ffffff;
          background: #ff6b35;
          border-color: #ff6b35;
        }

        &:active {
          opacity: 0.8;
        }
      }
    }
  }

  // 主要内容区域
  .main-content {
    flex: 1;
    display: flex;
    overflow: hidden;

    // 左侧目的地筛选
    .destination-sidebar {
      width: 160rpx;
      background: #FFFFFF;
      border-right: 1rpx solid #f0f0f0;
      flex-shrink: 0;

      .destination-scroll {
        height: 100%;
      }

      .destination-list {
        padding: 24rpx 0;

        .destination-item {
          padding: 24rpx 32rpx;
          border-left: 4rpx solid transparent;
          transition: all 0.3s ease;
          cursor: pointer;
          position: relative;

          &.active {
            background: #fff3e6;
            border-left-color: #FFC300;

            .destination-text {
              color: #FFC300;
              font-weight: bold;
            }

            &::after {
              content: '';
              position: absolute;
              right: 0;
              top: 50%;
              transform: translateY(-50%);
              width: 0;
              height: 0;
              border-left: 8rpx solid #FFC300;
              border-top: 8rpx solid transparent;
              border-bottom: 8rpx solid transparent;
            }
          }

          &:active {
            background: #f8f8f8;
          }

          .destination-text {
            font-size: 24rpx;
            color: #666666;
            display: block;
            text-align: center;
          }
        }
      }
    }

    // 右侧旅行商品列表
    .travel-content {
      flex: 1;
      overflow: hidden;
      box-sizing: border-box;
      padding-bottom: 20rpx;
      .travel-list-container {
        height: 100%;
        overflow: hidden;
        padding: 24rpx;
        box-sizing: border-box;

        .travel-item {
          display: flex;
          background: #FFFFFF;
          border-radius: 8rpx;
          margin-bottom: 12rpx;
          padding: 24rpx;
          cursor: pointer;
          padding-bottom: 40rpx;

          &:last-child {
            margin-bottom: 0;
            border-bottom: none !important;
          }

          .travel-image-wrapper {
            width: 150rpx;
            margin-right: 24rpx;
            border-radius: 12rpx;
            overflow: hidden;
            background: #f8f8f8;

            .travel-image {
              width: 100%;
              height: 100%;
            }
          }

          .travel-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            height: 180rpx;
            .travel-header {
              flex-grow: 1;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              .travel-name {
                font-size: 28rpx;
                color: #333333;
                line-height: 1.4;
                margin-bottom: 8rpx;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                line-clamp: 2;
                overflow: hidden;
                word-break: break-all;
              }

              .travel-price-section {
                display: flex;
                justify-content: space-between;
                align-items: flex-end;
                .price-info {
                  display: flex;
                  flex-direction: column;
                  align-items: flex-end;

                  .travel-price {
                    font-size: 24rpx;
                    color: #ff4d4f;
                    font-weight: bold;
                    margin-right: 12rpx;
                  }

                  .travel-price-tag {
                    font-size: 20rpx;
                    background-color: #FFC300;
                    padding: 4rpx 12rpx;
                    border-radius: 8rpx;
                    margin-top: 4rpx;
                  }
                  .travel-original-price {
                    font-size: 24rpx;
                    color: #999999;
                    text-decoration: line-through;
                  }
                }

                .travel-sales {
                  font-size: 24rpx;
                  color: #666666;
                }
              }
            }

            .travel-meta {
              display: flex;
              justify-content: flex-end;
              align-items: center;

              .travel-stock {
                font-size: 24rpx;
                color: #ff4d4f;
              }
            }
          }
        }
      }
    }
  }

  // 加载更多
  .load-more {
    text-align: center;
    padding: 32rpx;

    .load-more-text {
      font-size: 28rpx;
      color: #FFC300;
    }
  }

  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 32rpx;

    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 32rpx;
    }

    .empty-text {
      font-size: 28rpx;
      color: #999999;
      margin-bottom: 8rpx;
    }

    .empty-tip {
      font-size: 24rpx;
      color: #cccccc;
    }
  }

  // 错误状态
  .error-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 32rpx;

    .error-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 32rpx;
    }

    .error-text {
      font-size: 28rpx;
      color: #ff4d4f;
      margin-bottom: 8rpx;
    }

    .error-tip {
      font-size: 24rpx;
      color: #999999;
      margin-bottom: 32rpx;
    }

    .retry-btn {
      background: #FFC300;
      color: #FFFFFF;
      border: none;
      border-radius: 24rpx;
      padding: 16rpx 32rpx;
      font-size: 28rpx;
    }
  }

  // 加载状态
  .loading-state {
    text-align: center;
    padding: 32rpx;

    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #FFC300;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin: 0 auto 16rpx;
    }

    .loading-text {
      font-size: 28rpx;
      color: #666666;
    }
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  // 底部加载状态
  .bottom-loading {
    text-align: center;
    padding: 24rpx;

    .loading-text {
      font-size: 26rpx;
      color: #999999;
    }
  }

  // 没有更多数据
  .no-more {
    text-align: center;
    padding: 24rpx;

    .no-more-text {
      font-size: 26rpx;
      color: #cccccc;
    }
  }
}
</style>